/**
 * Copyright 2007-2008 Vidar Svansson
 *     
 * This file is part of JAdapter.
 * 
 * JAdapter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * JAdapter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with JAdapter.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.jadapter.adapters;

import java.util.Iterator;


/**
 * Adapter for String to Iterable.
 * <br></br><br></br> 
 * This is the internal data structure for Query&lt;String>.
 * 
 * @author Vidar Svansson
 * 
 * @since 0.1
 * 
 * @see org.jadapter.Query
 *
 */
public class IterableString implements Iterable<String> {

    private String string;
    
    public IterableString(String string){
        this.string = string;
    }
    
    public Iterator<String> iterator() {
        return new StringIterator(string);
    }
    
    public String toString() { return string; }
    
    /**
     * Iterator class for strings and character arrays.
     * The next method returns a char.
     * 
     * @author Vidar Svansson
     * @since 0.1
     */
    public static class CharIterator implements Iterator<Character> {
        private char[] seq;
        private int state = 0;
        
        public CharIterator(String string){
            this(string.toCharArray());
        }
 
        public CharIterator(char[] chars){
            this.seq = chars;
        }

        public boolean hasNext() {
            return state < seq.length;
        }

        public Character next() {
            return seq[state++];
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }       
    }
    
    /**
     * Iterator class for strings and character arrays.
     * The next method returns a String of length 1.
     * 
     * @author Vidar Svansson
     * @since 0.1
     */
    public static class StringIterator implements Iterator<String>{
        private CharIterator iterator;
        
        public StringIterator(String string){
            this.iterator = new CharIterator(string);
        }

        public boolean hasNext() {
            return iterator.hasNext();
        }

        public String next() {          
            return "" + iterator.next();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}
